const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const meetingSchema = new Schema({
  title: {
    type: String,
    required: true,
    trim: true
  },
  description: {
    type: String,
    trim: true
  },
  host: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  participants: [{
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User'
    },
    role: {
      type: String,
      enum: ['host', 'co-host', 'participant'],
      default: 'participant'
    },
    status: {
      type: String,
      enum: ['invited', 'joined', 'left'],
      default: 'invited'
    },
    joinedAt: {
      type: Date
    },
    leftAt: {
      type: Date
    },
    streamId: {
      type: String
    },
    isMuted: {
      type: Boolean,
      default: false
    },
    isVideoOff: {
      type: Boolean,
      default: false
    }
  }],
  startTime: {
    type: Date,
    default: Date.now
  },
  endTime: {
    type: Date
  },
  status: {
    type: String,
    enum: ['scheduled', 'in-progress', 'ended', 'cancelled'],
    default: 'scheduled'
  },
  settings: {
    allowJoinBeforeHost: {
      type: Boolean,
      default: false
    },
    muteOnEntry: {
      type: Boolean,
      default: true
    },
    enableChat: {
      type: Boolean,
      default: true
    },
    enableRecording: {
      type: Boolean,
      default: false
    },
    maxParticipants: {
      type: Number,
      default: 50
    }
  },
  recordings: [{
    fileId: {
      type: String
    },
    startTime: {
      type: Date
    },
    endTime: {
      type: Date
    },
    duration: {
      type: Number
    },
    fileSize: {
      type: Number
    },
    url: {
      type: String
    },
    status: {
      type: String,
      enum: ['processing', 'completed', 'failed']
    }
  }],
  chat: [{
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User'
    },
    message: {
      type: String
    },
    timestamp: {
      type: Date,
      default: Date.now
    },
    type: {
      type: String,
      enum: ['text', 'file', 'image']
    }
  }],
}, {
  timestamps: true
});

// 索引
meetingSchema.index({ host: 1, status: 1 });
meetingSchema.index({ 'participants.user': 1, status: 1 });
meetingSchema.index({ startTime: 1 });

const Meeting = mongoose.model('Meeting', meetingSchema);

module.exports = Meeting;